//TODO: Many toasts can be turned off, because they are just disturbing

package com.googlecode.eightqueenshaggle;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

//TODO some code in this class should be removed

public class BoardViewController extends Activity {

	public static final int MENU_NEW_GAME = 1;
	public static final int MENU_NEW_GAME_CMD = 2;
	public static final int MENU_VIEW_SOLUTIONS = 3;
	public static final int MENU_QUIT = 4;

	public EightQueens eqHandler=null;

	GridView gridview;

	// converts grid position into logical coordinates (a0 is in lower left
	// corner)
	public Coord gridPos2LogicalPos(int position) {

		int dim1 = this.puzzle.dim1;
		int dim2 = this.puzzle.dim2;

		return new Coord((dim1 - 1) - (position - position % dim2) / dim2,
				position % dim2);

	}

	// the chess board consists of bright and dark cells
	public Boolean isDark(int x, int y) {

		if (x % 2 == 0 && y % 2 == 0 || x % 2 == 1 && y % 2 == 1) // this is a
			// dark cell
			return true;

		else
			return false;

	}

	public Puzzle puzzle;
	public Solution solution;

	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.board);

		eqHandler=(EightQueens) this.getApplication();
		eqHandler.boardViewControllerHandler=this;


		// set up a little game
		// TODO: The user has no choice to influence the size of the field
		// TODO: Make a dialog and let the user chose from different games
		puzzle = new Puzzle(8, 8, 8, 91, "classicalPuzzle");
		solution = new Solution(puzzle);

		gridview = (GridView) findViewById(R.id.GridView);
		gridview.setNumColumns(puzzle.dim2); // Make sure there are dim2
		// coloumns

		gridview.setAdapter(new BoardViewImageAdapter(this));

		gridview.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {

				ImageView iv = (ImageView) v;

				// if the position is vacant
				Coord logicalPosition = gridPos2LogicalPos(position);
				if (solution.checkFree(logicalPosition.x, logicalPosition.y)) {

					// if the position is valid,place a queen
					if (solution.addQueen(logicalPosition.x, logicalPosition.y)) {

						// determine wheter we need to draw a bright/dark cell
						if (isDark(logicalPosition.x, logicalPosition.y))
							iv.setImageResource(R.drawable.field_occupied_dark);
						else
							iv
									.setImageResource(R.drawable.field_occupied_bright);

						Toast
								.makeText(
										BoardViewController.this,
										"A queen was placed at row "
												+ logicalPosition.x + ",col "
												+ logicalPosition.y,
										Toast.LENGTH_SHORT).show();

					}
					// the position is not valid
					else {
						Toast.makeText(
								BoardViewController.this,
								"invalid position at row " + logicalPosition.x
										+ ",col " + logicalPosition.y,
								Toast.LENGTH_SHORT).show();
					}
				}
				// if there is already a queen there
				else if (solution.checkQueen(logicalPosition.x,
						logicalPosition.y)) {

					// remove a queen
					solution.removeQueen(logicalPosition.x, logicalPosition.y);

					// determine wheter we need to draw a bright/dark cell
					if (isDark(logicalPosition.x, logicalPosition.y))
						iv.setImageResource(R.drawable.field_empty_dark);
					else
						iv.setImageResource(R.drawable.field_empty_bright);

					Toast.makeText(
							BoardViewController.this,
							"A queen was removed at row " + logicalPosition.x
									+ ",col " + logicalPosition.y,
							Toast.LENGTH_SHORT).show();

				}

				// grey out those tiles that can not be chosen anymore
				// TODO: This is a little bit dirty, because we draw the the
				// cells twice, remove the above setImageResource commands
				for (int i = 0; i < puzzle.dim1 * puzzle.dim2; i++) { // iterate
					// over
					// all
					// cells

					int x = gridPos2LogicalPos(i).x;
					int y = gridPos2LogicalPos(i).y;

					// TODO: maybe this would be nicer with a switch
					if (!solution.checkQueen(x, y) && !solution.checkFree(x, y)) { // position
						// is
						// not
						// free
						// and
						// does
						// not
						// contain
						// a
						// queen

						// make unfree cells unclickable
						((ImageView) gridview.getChildAt(i)).setClickable(true);

						if (isDark(x, y)) {
							((ImageView) gridview.getChildAt(i))
									.setImageResource(R.drawable.field_greyed);

						} else {
							((ImageView) gridview.getChildAt(i))
									.setImageResource(R.drawable.field_greyed);
						}

					}

					if (!solution.checkQueen(x, y) && solution.checkFree(x, y)) { // these
						// are
						// normal
						// free
						// cells
						// that
						// can
						// still
						// be
						// clicked

						((ImageView) gridview.getChildAt(i))
								.setClickable(false);

						if (isDark(x, y)) {
							((ImageView) gridview.getChildAt(i))
									.setImageResource(R.drawable.field_empty_dark);

						} else {
							((ImageView) gridview.getChildAt(i))
									.setImageResource(R.drawable.field_empty_bright);
						}

					}

					if (solution.checkQueen(x, y)) { // a cell with a queen

						((ImageView) gridview.getChildAt(i))
								.setClickable(false);

						if (isDark(x, y)) {
							((ImageView) gridview.getChildAt(i))
									.setImageResource(R.drawable.field_occupied_dark);

						} else {
							((ImageView) gridview.getChildAt(i))
									.setImageResource(R.drawable.field_occupied_bright);
						}

					}

				}

				// print the remaining amount of queens
				((TextView) findViewById(R.id.TV_QueensLeft)).setText(""
						+ (puzzle.amountQueens - solution.getCurQueenCount()));

				// check if a solution is achieved
				if (solution.queensLocations.size() == puzzle.amountQueens) {

					/*
					 * Toast.makeText(BoardViewController.this,
					 * "Solution found", Toast.LENGTH_SHORT).show();
					 */

					// TODO publish the solution Through Haggle
					this.publishSolution();

					// goto to Victory View
					Intent intent = new Intent(BoardViewController.this,
							VictoryViewController.class);
					startActivity(intent);
					finish();
				}

			}

			private void publishSolution() {
				

			}
		});
	}

	/* Creates the menu items */
	// TODO: There should be a way to go back to the main menu
	// TODO: The back button should also lead the user back to the main menu
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		menu.add(0, MENU_NEW_GAME, 0, "New Game");
		menu.add(0, MENU_NEW_GAME_CMD, 0, "New Game (cmd)");
		menu.add(0, MENU_VIEW_SOLUTIONS, 0, "View Solutions");
		menu.add(0, MENU_QUIT, 0, "Quit");
		return true;
	}

	/* Handles item selections */
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_NEW_GAME:
			newGame(); // TODO: This should call the GAME_TYPE dialog first.
			return true;
		case MENU_NEW_GAME_CMD:
			//newGameCmd();
			return true;
		case MENU_VIEW_SOLUTIONS:
			viewSolutions();
			return true;
		case MENU_QUIT:
			
			
			this.finish();
			return true;
		}
		return false;
	}

	private void viewSolutions() {
		// TODO view Solutions from DB

		Intent intent = new Intent(this, SolutionExplorerViewController.class);
		startActivity(intent);
	}

	/*private void newGameCmd() {
		Intent intent = new Intent(this, CmdController.class);
		startActivity(intent);

		
		finish();
	}*/

	private void newGame() {
		Intent intent = new Intent(this, BoardViewController.class);
		startActivity(intent);

		
		finish();
	}

	// init haggle when the app starts
	@Override
	public void onStart() {
		super.onStart();

	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent intent = new Intent(this, MainMenuController.class);
			startActivity(intent);
			finish();
        	//moveTaskToBack(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
	
}
